//
//  VerifyMobileViewController.m
//  HuaMuJinRong
//
//  Created by 吴建东 on 16/4/20.
//  Copyright © 2016年 EIMS. All rights reserved.
//

#import "VerifyMobileViewController.h"
#import "ChangeMobileViewController.h"
#import "NSString+Shove.h"
#import "ChangePasswordViewController.h"
#import "SetSafeEmailTwoViewController.h"

@interface VerifyMobileViewController ()<HTTPClientDelegate>
@property (weak, nonatomic) IBOutlet UILabel     *mobileLabel;
@property (weak, nonatomic) IBOutlet UILabel     *verifyLabel;
@property (weak, nonatomic) IBOutlet UITextField *verifyNumTextfield;
@property (weak, nonatomic) IBOutlet UIButton    *verifyButton;
@property (weak, nonatomic) IBOutlet ClickButton *nextButton;
@property (weak, nonatomic) IBOutlet UIButton    *questionButton;

@property (nonatomic, strong) NetWorkClient *requestClient;
@property (nonatomic, assign) BOOL          isLoading;
@property (nonatomic, assign) NSInteger     requestType;

@end

@implementation VerifyMobileViewController
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (_requestClient != nil) {
        [_requestClient cancel];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
   
    self.view.backgroundColor = KbackgroundColor;
    [self initNavBarTitle:self.naviTitle andLeftItemName:@"返回" andRightItemName:@""];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self initView];
    
    [self initData];
}

- (void)backClick {
    if (self.viewType == ResetDealPassword) {
        [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count - 3] animated:YES];
    }else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - Action
- (IBAction)verifyButtonClick:(id)sender {
    [self getVerifyCodeRequest];
}

- (IBAction)nextButtonClick:(id)sender {
    if (_verifyNumTextfield.text.length <= 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入验证码"];
        return;
    }
    [self changeRequest];
}

- (IBAction)questionButtonClick:(id)sender {
    
    
}

- (void)timeDown {
    __block NSInteger timeout = 60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                
                [_verifyButton setTitle:@"发送验证码" forState:UIControlStateNormal];
                _verifyButton.enabled = YES;
            });
        }else{
            int seconds = timeout % 61;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                
                [_verifyButton setTitle:[NSString stringWithFormat:@" (%@) ",strTime] forState:UIControlStateNormal];
                _verifyButton.enabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

#pragma mark - Data
- (void)initData {
    
    //[self getVerifyCodeRequest];
}

- (void)changeRequest {
    if (_isLoading) {
        [SVProgressHUD showImage:nil status:@"正在请求，请稍候再试..."];
        return;
    }
    _requestType = 2;
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"517" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"id"];
    [parameters setObject:_verifyNumTextfield.text forKey:@"code"];
    [parameters setObject:AppDelegateInstance.userInfo.mobile forKey:@"mobile"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
        
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}

- (void)getVerifyCodeRequest {
    if (_isLoading) {
        [SVProgressHUD showImage:nil status:@"正在请求，请稍候再试..."];
        return;
    }
    _requestType = 1;
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"4" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    if ([_mobileStr isPhone]) {
        [parameters setObject:_mobileStr forKey:@"cellPhone"];
    }else {
        [SVProgressHUD showImage:nil status:@"手机号码格式不正确！"];
        return;
    }
    [parameters setObject:@"1" forKey:@"type"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
        
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}

#pragma - 网络数据回调代理
- (void)startRequest {
    _isLoading = YES;
}

// 返回成功
- (void)httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj {
    _isLoading = NO;
    NSDictionary *dics = obj;
    DLOG(@"dic=%@",dics);
    if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-1"]) {
        if (_requestType == 1) {
            [SVProgressHUD showSuccessWithStatus:[dics objectForKey:@"msg"]];
            
            [self timeDown];
            NSString *mobile = AppDelegateInstance.userInfo.mobile;
            if (mobile.length > 10) {
                _mobileLabel.text = [NSString stringWithFormat:@"短信已发送手机号 %@****%@",[mobile substringToIndex:3],[mobile substringFromIndex:mobile.length-4]];
            }else {
                _mobileLabel.text = [NSString stringWithFormat:@"短信已发送手机号 %@",mobile];
            }
        }else if (_requestType == 2) {
            [SVProgressHUD showSuccessWithStatus:[dics objectForKey:@"msg"]];
            
            if (self.viewType == ChangeBindMobile) {
                ChangeMobileViewController *changeMobile = [[ChangeMobileViewController alloc] init];
                changeMobile.isChangeBank = NO;
                [self.navigationController pushViewController:changeMobile animated:YES];
            }else if (self.viewType == ChangeBankMobile) {
                ChangeMobileViewController *changeMobile = [[ChangeMobileViewController alloc] init];
                changeMobile.isChangeBank = YES;
                [self.navigationController pushViewController:changeMobile animated:YES];
            }else if (self.viewType == ResetDealPassword) {
                ChangePasswordViewController *changePwd = [[ChangePasswordViewController alloc] init];
                changePwd.naviTitle = @"重置交易密码";
                changePwd.editType = ChangeTradePwd;
                [self.navigationController pushViewController:changePwd animated:YES];
                
            }else if (self.viewType == ChangeSafeEmail) {
                SetSafeEmailTwoViewController *SetSafeEmailTwoView = [[SetSafeEmailTwoViewController alloc] init];
                [self.navigationController pushViewController:SetSafeEmailTwoView animated:YES];
            }
        }
        
        
    }else if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-2"]) {
        
        [ReLogin outTheTimeRelogin:self];
    }else {
        if (_requestType == 1) {
            _mobileLabel.text = [NSString stringWithFormat:@"短信发送失败，请重新获取!"];
        }
        [SVProgressHUD showImage:nil status:[dics objectForKey:@"msg"]];
    }
    
}

// 返回失败
- (void)httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error {
    
}

// 无可用的网络
- (void)networkError {
   // [SVProgressHUD showErrorWithStatus:@"网络不给力，请检查您的网络设置"];
}


#pragma mark - View
- (void)initView {
    _nextButton.clipsToBounds = YES;
    _nextButton.layer.cornerRadius = kCornerRadius;
    
    _mobileLabel.font = KFontSize(14.0);
    _verifyLabel.font = KFontSize(15.0);
    _verifyNumTextfield.font = KFontSize(14.0);
    _nextButton.titleLabel.font = KFontSize(16.0);
    _questionButton.titleLabel.font = KFontSize(13.0);
    _verifyButton.titleLabel.font = KFontSize(13.0);
    _verifyButton.titleLabel.adjustsFontSizeToFitWidth = YES;
    
    NSString *mobile = AppDelegateInstance.userInfo.mobile;
    if (mobile.length > 10) {
        _mobileLabel.text = [NSString stringWithFormat:@"手机号 %@****%@",[mobile substringToIndex:3],[mobile substringFromIndex:mobile.length-4]];
    }else {
        _mobileLabel.text = [NSString stringWithFormat:@"手机号 %@",mobile];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
